package dao

import (
	"context"
	"encoding/json"

	"github.com/google/uuid"

	"open/internal/model"
	"open/internal/model/event"
	"open/internal/types"
	"open/pkg/log"
)

// Send 发送事件
func (d *Dao) Send(ctx context.Context, event event.Event) error {
	payload, _ := json.Marshal(event)
	log.FromContext(ctx).Infof("nsq publish: %s", payload)
	return d.producer.Publish(event.Topic(), payload)
}

// TxSend 事务化消息
func (d *Dao) TxSend(ctx context.Context, event event.Event) error {
	if events, ok := ctx.Value(eventKey).(map[string]map[int64][]byte); ok {
		if _, ok := events[event.Topic()]; !ok {
			events[event.Topic()] = make(map[int64][]byte)
		}
		payload, _ := json.Marshal(event)
		nsqMsg := &model.EventMessage{
			Topic:   event.Topic(),
			MsgKey:  uuid.New().String(),
			Payload: payload,
			Status:  types.NSQInit,
		}
		if err := d.FromContext(ctx).Create(&nsqMsg).Error; err != nil {
			return err
		}
		events[event.Topic()][nsqMsg.ID] = payload
	}
	return nil
}
